package com.kwk.messagepushding;

import com.kwk.messagepushding.util.ModbusTcpCoilReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;

@EnableConfigurationProperties
//扫描定时器
@EnableScheduling
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class MessagePushDingApplication {

    public static void main(String[] args) {
        SpringApplication.run(MessagePushDingApplication.class, args);
    }
    // 使用CommandLineRunner接口在应用启动时运行代码
    @Service
    static class SocketServerRunner implements CommandLineRunner {

        // 指定Socket服务器监听的端口
        private static final int PORT = 502;


        @Override
        public void run(String... args) throws Exception {
            // 创建一个ServerSocket来监听指定端口
            try (ServerSocket serverSocket = new ServerSocket(PORT)) {
                System.out.println("Socket服务器已启动，监听端口 " + PORT);

                // 无限循环，持续接受客户端连接
                while (true) {
                    // 接受一个客户端连接，返回Socket对象
                    Socket clientSocket = serverSocket.accept();
                    System.out.println("客户端已连接: " + clientSocket.getInetAddress().getHostAddress()+":"+clientSocket.getPort());
                    // 为每个客户端连接启动一个新线程来处理
                    new ClientHandler(clientSocket).start();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 客户端处理器类，负责处理与客户端的通信
    static class ClientHandler extends Thread {

        // 客户端Socket对象
        private final Socket clientSocket;

        public ClientHandler(Socket socket) {
            this.clientSocket = socket;
        }

        @Override
        public void run() {
            try (
                    DataInputStream input = new DataInputStream(clientSocket.getInputStream());
                    // 如果需要发送响应，可以创建相应的输出流
                    DataOutputStream output = new DataOutputStream(clientSocket.getOutputStream());
            ) {
                byte[] buffer = new byte[1024]; // 缓冲区大小可以根据需要调整
                int bytesRead;
                while ((bytesRead = input.read(buffer)) != -1) {
                    // 读取到数据，处理数据
                    byte[] data = new byte[bytesRead];
                    System.arraycopy(buffer, 0, data, 0, bytesRead);
                    // 打印接收到的数据（以十六进制形式）
                    StringBuilder sb = new StringBuilder();
                    for (byte b : data) {
                        sb.append(String.format("%02X ", b));
                    }
                    String readMsg = sb.toString().trim().replace(" ", "");
                    System.out.println("TX: " + readMsg);

                    byte[] modbusRequest = ModbusTcpCoilReader.createModbusRequest(readMsg);
//                     如果需要，可以在这里添加处理数据的逻辑
                    String outputsb = ModbusTcpCoilReader.modbusTcpFunc(modbusRequest);
                    System.out.println("RX：" + outputsb);
//                     如果需要发送响应给客户端，可以在这里使用output.write(...)方法
                    output.write(outputsb.getBytes());
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    // 关闭客户端Socket连接
                    clientSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println("客户端断开连接: " + clientSocket.getInetAddress().getHostAddress()+":"+clientSocket.getPort());
            }
        }
    }
}
